<template>
	<view class="time-manage-page">
		<Tips title="小贴士" :des="des" />
		<view class="mange-time-slot">
			<view class="available-use-time" @click="setTimeLimit">
				<view class="left-txt">
					设置每日应用可用总时长					
				</view>
				<view class="time">
					<view>{{ timeTotal}} </view>
					<image src="/static/icon/arrow-right.png" style="width: 20px;height: 20px;"></image>
				</view>
			</view>
			<view class="title">禁用时间段管理设置</view>
			<view class="des">可以为每天设置多个时间段， 该时间段内仅仅短信，电话,闹钟可用</view>
			<view class="week">
				<view v-for="(w, index) in weeks" :key="w.e" class="week-day" :class="{'activeWeekDay': time.currentActive.index === index, 'haveData': queryLen(w)}"  @click="() => clickWeek(index, w.e)">
					<view class="e">{{w.e}}</view>
					<view class="c">{{w.c}}</view>
				</view>
			</view>
			<view class="time-manage">
				<view class="bg"></view>
				<view class="header">
					<view class="title">设置当天禁用时间段</view>
					<view class="btn" @click="usePreDayData">引用前一天设置的内容</view>
				</view>
				<view v-if="currentWeek.length > 0 && showTime" class="control-time-list-item" v-for="(t, i) in currentWeek" :key="i">
					<view class="control-time">
						<view class="serial">
							<image style="width: 40px; height: 40px;" :src="weekImg[i]" />
						</view>
					</view>
					<view class="time-input">
						<timeVue :startTime="t.startTime" :endTime="t.endTime" :preEndTime="preEndTime()" @onSelectStartTimeCB="(start_time) => onSelectStartTimeCB(start_time, i)" @onSelectEndTimeCB="(end_time, cb) =>onSelectEndTimeCB(end_time, i, cb)"/>
					</view>
					<view class="action-btn">
						<!-- <view class="setting">设置</view> -->
						<view class="dele" @click="() => removeTime(i)">
							<image src="/static/icon/icon_day_delete.png" style="width: 30px; height: 30px;" />
						</view>

					</view>
				</view>
				<view v-else class="empt">
					<Empt description="请添加禁用时间段" />
				</view>
				<view class="add-white-app-post-bottom">
					<!-- <van-icon name="add" color="#fff" /> -->
					<image src="/static/icon/add.png" style="width:20px; height:20px"></image>
					<view class="txt" @click="addDisableTime">添加禁用时间段</view>
				</view>
			</view>
		</view>
		<uni-popup 
			ref="showPopupRef"
			type="bottom"
			background-color="#fff">
			<view class="top-switch">
				<view class="title add-close">
					<view class="title-position">设置每日可用时长</view>
					<view></view>
					<!-- <van-icon  name="cross" size="16" class="close-icon-postion" @click="() => closePopup()" v-if="!showPicker"/> -->
					<view @click="() => closePopup()" v-if="!showPicker"><image src="/static/icon/close.png" style="width: 20px;height: 20px;" class="close-icon-postion"></image></view>
				</view>
				<view class="txt-switch"  :class="{'customSwitch': !showPicker}">
					<view class="left-txt">是否开启每日时长设置</view>
					<switch :checked="checked" @change="onChangeSwitch"  color="#2BC888" style="transform:scale(0.7)"/>
				</view>
			</view>
			<view v-if="showPickerTime">
				<picker-view v-if="showPicker"  :class="{'hideHeightStyle': !showPicker}" @change="changeTime" :value="defaultIndex"  :indicator-style="indicatorStyle" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in columns[0].values" :key="index">{{item}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in columns[1].values" :key="index">{{item}} </view>
					</picker-view-column>
				</picker-view>
			</view>
			<view class="time-lang-control" v-if="showPicker">
				<view class="base-time-lang oncancel-btn" @click="onCancelAvailableDuration">取消</view>
				<view class="base-time-lang onSure-btn" @click="onConfirmAvailableDuration">确定</view>
			</view>
			
				
				
				<!-- <picker
				  ref="vanPickerRef"
				  :class="{'hideHeightStyle': !showPicker}"
				  show-toolbar
				  toolbar-position="bottom"
				  :columns="columns"
				  :default-index="defaultIndex"
				  @cancel="onCancelAvailableDuration"
				  @confirm="onConfirmAvailableDuration"
				  cancelButtonText="取消"
				  confirmButtonText="确定"
				  custom-class="custom-flotter"
				/> -->
		</uni-popup>
		
		
		<uni-popup
			ref="newAddTimeRef"
			type="bottom"
			background-color="#fff"
		>
			<view class="top-switch">
				<view class="title">设置禁用时间</view>
			</view>
			<view class="new-add-time-content">
				<timeVue v-if="newAddTimePopup" :startTime="STARTTIME" :endTime="addEndTime" :preEndTime="preEndTime()" @onSelectStartTimeCB="(start_time) => addStartTimeHandler(start_time, 0)" @onSelectEndTimeCB="(end_time, cb) =>addEndTimeHandler(end_time, 0, cb)"/>
			</view>
			<view class="footer">
				<button class="basic-footer-new-time cancel-new-time" size="small" color="#969799" @click="onCancelNewAddTime">取消</button>
				<button class="basic-footer-new-time enter-new-time" size="small" color="#57bf6a" :disabled="disabledAddTime" @click="onAddNewTime">确定</button>
			</view>
		</uni-popup>
		
		<view class="showPickerTimeModal" >
			<Loading />
		</view>
	</view>
	
</template>

<script lang="ts" setup>
	import {computed,  ref, onMounted, nextTick, watch} from 'vue'
	import { homeServer } from '@/common/index';
	import Tips from '@/components/tips/index.vue';
	import Empt from "@/components/Empt/index.vue"
	import Loading from "@/components/loading.vue"
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import timeVue from './time.vue';
	import { mock } from "@/utils/index"
	import { useBound } from "@/hooks/useBound.ts"
	import { onUnload} from "@dcloudio/uni-app"
	const {tipBoundStudent, studentIsEmpt} = useBound();
		
	const newAddTimeRef = ref();
		
	const switchAvailabelTime = ref({});
	const showPicker = ref(false);
	const disabledAddTime = ref(false)
	
	const vanPickerRef = ref()
	
	const showPopupRef = ref()
	const showPickerTime = ref(false)
	
	
	const  closePopup = () => {
	  showPopup.value = false
	  showPopupRef.value.close()
	  console.log('showPopupRef.value',showPopup.value, showPopupRef.value)
	}
	
	const indicatorStyle = ref("height: 50px")
	const currentTime = ref({
		index: [],
		value: []
	})
	const changeTime= ({ detail }) => {
		currentTime.value.index = detail.value;
		const [h_index, m_index] = detail.value
		currentTime.value.value = [columns.value[0].values[h_index], columns.value[1].values[m_index]]
	}
	
	
	const setMockData = () => {
		// mock 数据
		const data = mock.APP_TIME_CONTROL.data
		patternParents.value = data
		if(Array.isArray(data.patternParentSlots)){
			data.patternParentSlots?.forEach(t => {
				const {dayTheWeek, patternTimeScopes} = t;
				if(dayTheWeek === 1){
					time.value.Mon = patternTimeScopes
				}
				if(dayTheWeek === 2){
					time.value.Tue = patternTimeScopes
				}
				if(dayTheWeek === 3){
					time.value.Web = patternTimeScopes
				}
				if(dayTheWeek === 4){
					time.value.Thur = patternTimeScopes
				}
				if(dayTheWeek === 5){
					time.value.Fri = patternTimeScopes
				}
				if(dayTheWeek === 6){
					time.value.Sat = patternTimeScopes
				}
				if(dayTheWeek === 7){
					time.value.Sun = patternTimeScopes
				}
			})
		}
	}
	
	const newAddTimePopup = ref(false) // 新添加一个禁用时间，需要在弹窗里面修改
	const addStartTime = ref("00:00");
	const addEndTime = ref("23:59");
	const STARTTIME = computed(() => addStartTime.value)
	const addStartTimeHandler = (start_time, i) => {
		const w = time.value.currentActive.week;
		// console.log("w", w, time.value[w])
		// let newTime = {
		// 	startTime: start_time
		// }
		// if(time.value[w][i]){
		// 	newTime = {
		// 		...time.value[w][i],
		// 		startTime: start_time
		// 	}
		// }
		// time.value[w][i] = newTime;
		addStartTime.value = start_time
		// patternParentsSetting();
	}
	const addEndTimeHandler = (end_time, i, cb) => {
		const w = time.value.currentActive.week;
		if(!validateTime(addStartTime.value, end_time)){
			uni.showToast({
				title:"结束时间不能小于开始时间",
				icon:"none",
				duration:3000
			})
			return;
		}
		// let newEndTime = {
		// 	endTime: end_time
		// }
		// if(time.value[w][i]){
		// 	newEndTime = {
		// 		...time.value[w][i],
		// 		endTime: end_time
		// 	}
		// }
		// time.value[w][i] = newEndTime
		// patternParentsSetting();
		addEndTime.value = end_time
		cb?.()
	}
		
	function convertMinutesToHoursAndMinutes(totalMinutes) {  
	    // 计算小时数  
	    const hours = Math.floor(totalMinutes / 60);  
	    // 计算剩余的分钟数  
	    const remainingMinutes = totalMinutes % 60;  
	  
	    // 构造结果数组  
	    const resultArray = [hours, remainingMinutes];  
	  
	    // 格式化字符串  
	    const formattedString = `${hours.toString().padStart(2, '0')}小时${remainingMinutes.toString().padStart(2, '0')}分钟`;  
	  
	    // 返回结果数组和格式化字符串  
	    return {  
	        array: resultArray,  
	        string: formattedString  
	    };  
	}  
	
	function calculateHourMinuteIndexes(seconds) {  
	    // 计算小时数和分钟数  
	    const hours = Math.floor(seconds / 3600); // 每小时有3600秒  
	    const minutes = Math.floor((seconds % 3600) / 60); // 剩余秒数转换为分钟  
	  
	    // 获取小时和分钟在各自范围内的索引  
	    const hourIndex = hours % 24; // 如果小时数超过23，则取模得到0-23范围内的索引  
	    const minuteIndex = minutes; // 分钟数本身就是0-59范围内的索引  
	  
	    // 返回一个包含小时索引和分钟索引的数组  
	    return [hourIndex, minuteIndex - 1];  
	}
	
	
	function calculateTotalMinutes(timeArray) {  
	    // 确保传入的数组有两个元素，且格式正确  
	    if (timeArray.length !== 2 ||   
	        !timeArray[0].endsWith('小时') ||   
	        !timeArray[1].endsWith('分钟')) {  
	        throw new Error('Invalid input format');  
	    }  
	  
	    // 提取小时和分钟  
	    const hoursStr = timeArray[0].slice(0, -2); // 移除"小时"字符串  
	    const minutesStr = timeArray[1].slice(0, -2); // 移除"分钟"字符串  
	  
	    // 将字符串转换为数字  
	    const hours = parseInt(hoursStr, 10);  
	    const minutes = parseInt(minutesStr, 10);  
	  
	    // 计算总分钟数  
	    const totalMinutes = hours * 60 + minutes;  
	  
	    return totalMinutes;  
	} 
	
	const patternParents = ref([]); //  一周禁用时间段
	// 查询周一到周日禁用时间段
	const patternParentsQuery = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			return;
		}
		try{
			const { status, data} = await homeServer.patternParentsQuery({studentId});
			if(status === '200'){
				patternParents.value = data
				if(Array.isArray(data.patternParentSlots)){
					data.patternParentSlots?.forEach(t => {
						const {dayTheWeek, patternTimeScopes} = t;
						if(dayTheWeek === 1){
							time.value.Mon = patternTimeScopes
						}
						if(dayTheWeek === 2){
							time.value.Tue = patternTimeScopes
						}
						if(dayTheWeek === 3){
							time.value.Web = patternTimeScopes
						}
						if(dayTheWeek === 4){
							time.value.Thur = patternTimeScopes
						}
						if(dayTheWeek === 5){
							time.value.Fri = patternTimeScopes
						}
						if(dayTheWeek === 6){
							time.value.Sat = patternTimeScopes
						}
						if(dayTheWeek === 7){
							time.value.Sun = patternTimeScopes
						}
					})
				}
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	// 设置是否开启
	const settingSwitch = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			showPopup.value = false
			showPopupRef.value.close()
			return;
		}
		try{
			const dailySettingSwitch = checked.value ? 1 : 0
			const {status, data} = await homeServer.settingSwitch({
				dailySettingSwitch: dailySettingSwitch, // 日常时间段管控是否生效【1-开启,管控生效 默认，0-管控不生效】
				weekendSettingSwitch: dailySettingSwitch, //周末时间段管控是否生效【1-开启,管控生效 默认，0-管控不生效】
				studentId,
				type: 1, // 模式类型【1-上学模式，2-假期模式】
			});
			if(status === '200'){
				switchAvailabelTime.value = {
					...switchAvailabelTime.value,
					dailySettingSwitch: dailySettingSwitch,
				}
				// queryControlSwitchAndAvailableTime()
				
				// if(dailySettingSwitch === 0){ // 此时设置了不能设置时间，因此需要去掉之前设置的时间
				// 	timeTotal.value = defaultTimeTips
				// 	minuteTotal.value = 0
				// 	// timeTotal.value="00小时00分钟"
				// 	defaultIndex.value = ['','']
				// 	await settingAvailableTime();
				// 	queryControlSwitchAndAvailableTime();
				// }
				if(!notShowMsg.value){
					uni.showToast({
						title:"设置成功",
						icon: 'success',
						complete() {
							showPicker.value =  dailySettingSwitch === 1
							if(dailySettingSwitch === 0){
								showPopup.value = false
								showPopupRef.value.close()
							}
						}
					})
				}
				notShowMsg.value = false
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	// 引用前一天设置的时间
	const usePreDayData = () => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		const weeks = ['Mon', 'Tue', 'Web', 'Thur', 'Fri', 'Sat', 'Sun']; // 星期一到星期天依次类推
		const index = weeks.findIndex(t => t === time.value.currentActive.week);
		const preDayKey = index === 0 ? weeks[weeks.length - 1]: weeks[index -1]; // 如果当前处于周一，那么直接使用星期天的设置的时间
		const cloneData = JSON.parse(JSON.stringify(time.value[preDayKey]));
		time.value[time.value.currentActive.week] = cloneData;
		showTime.value = false;
		setTimeout(() => {
			showTime.value = true
			patternParentsSetting();
		});
	}
	
	const showPopup =  ref(false)

	const checked = ref(false);
	const defaultTimeTips = "未设置时间"
	const timeTotal = ref(defaultTimeTips)
	const minuteTotal = ref();
	const defaultIndex = ref([0,0]);
	
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	
	const notShowMsg = ref(false)
	
	
	
	
	// 设置是否可用
	const settingAvailableTime = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			return;
		}
		try{
			const params = {
				studentId,
				dailyAvailableTime: minuteTotal.value,
				dailyAvailableTimeName: timeTotal.value,
				type: 1,
				weekendAvailableTime: minuteTotal.value,
				weekendAvailableTimeName: timeTotal.value
			};
			const {status, data} = await homeServer.settingAvailableTime(params);
			if(status === '200'){
				uni.showToast({
					title:"设置成功"
				})
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	const onChangeSwitch = ({detail}) => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		console.log('switch开关状态', detail)
		// showPicker.value = detail
		checked.value = detail.value
		timeTotal.value = defaultTimeTips
		defaultIndex.value = [0, 0]
		currentTime.value.index = [0,0];
		currentTime.value.value = ["00小时", "01分钟"]
		// .van_picker.setIndexes([0])
		console.log("vanPickerRef.value", vanPickerRef.value)
		// vanPickerRef.value.setIndexes([0, 0])
		settingSwitch();
		
	
		
		nextTick(() => {
			setTimeout(() => {
				showPickerTime.value = false
				defaultIndex.value = [0, 0];
				showPickerTime.value = true
			}, 1000)
		})
						
	}
	
	const setTimeLimit = () => {
		if(studentIsEmpt.value){
			tipBoundStudent();
			return
		}
		showPopup.value = true
		showPopupRef.value.open()
		
			nextTick(() => {
					showPickerTime.value = false
					setTimeout(() => {
						showPickerTime.value = true
					}, 1000)
			})
						
		console.log('有值吗', defaultIndex.value)
	}
	const generaTime = (len: number, unit: string, isFull) => {
		return Array.from({length:len }, (_, index) => {
			if(isFull){
				if(index === 0) return  `00${unit}`;
				return index.toString().padStart(2, '0') + unit
			} else {
				// if(index === 0) return  `00${unit}`;
				const INDEX = index + 1
				return INDEX.toString().padStart(2, '0') + unit
			}
		})
	}
	const columns = ref([
		{
			values: generaTime(24, '小时', true), // true: 0-24
			defaultIndex: 1
		},
		{
			values: generaTime(60, '分钟', false), // false 1-24
			defaultIndex: 1
	  },
	])

	
	const onCancelAvailableDuration = (r) => {
		console.log('取消', r)
		if(timeTotal.value === defaultTimeTips && checked.value ) {
			console.log("页面销毁了 需要重置时间开关")
			notShowMsg.value = true
			onChangeSwitch({detail: false})
			showPicker.value = false
		}
		showPopup.value = false;
		showPopupRef.value.close()
	}
	
	const onConfirmAvailableDuration = () => {
		console.log('是否为0', currentTime.value)
		if(currentTime.value.index.length === 0 || currentTime.value.value.length === 0){
			console.log("没有选中任何时间")
			return;
		}
		if(Number(switchAvailabelTime.value.dailySettingSwitch) === 1){
			const {index, value} = currentTime.value
			timeTotal.value = value?.reduce((p,n) => p += n, '');
			console.log('index', index)
			defaultIndex.value = index;
			showPopup.value = false;
			showPopupRef.value.close()
			minuteTotal.value = calculateTotalMinutes(value);
			settingAvailableTime();
		} else {
			showPopup.value = false;
			showPopupRef.value.close()
			// uni.showToast({
			// 	title: "请先开启每日时长设置，再设置可用时间",
			// 	icon:"none"
			// })
		}
		
	}
	
	//获取每日应用可用总时长
	const queryControlSwitchAndAvailableTime = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			return;
		}
		try{
			const {status, data} = await homeServer.queryControlSwitchAndAvailableTime({studentId});
			console.log("data", data)
			if(status === '200'){
				if(Number(data.dailySettingSwitch) === 1){ // 1: 可以设置时间 0： 时间设置被禁用
					timeTotal.value = data.dailyAvailableTimeName;
				} else {
					timeTotal.value = defaultTimeTips
				}
				checked.value = data.dailySettingSwitch === 1 ? true : false;
				// defaultIndex.value = calculateHourMinuteIndexes(data.dailyAvailableTime * 60);
				switchAvailabelTime.value = data;
				showPicker.value = data.weekendSettingSwitch === 1
				
				nextTick(() => {
					showPickerTime.value = false
					setTimeout(() => {
						defaultIndex.value = calculateHourMinuteIndexes(data.dailyAvailableTime * 60);
						showPickerTime.value = true
					}, 1000)
				})
				
			} else {
				console.log("接口非200")
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	} 
	

	
	onMounted(async () => {
		if(!mock.isLogged()){
			console.log('用户登录了，不应该再次进入这里')
			setMockData()
		} else {
			await queryControlSwitchAndAvailableTime();
			await patternParentsQuery();	
			nextTick(() => {
				showPickerTime.value = false
				setTimeout(() => {
					showPickerTime.value = true
				}, 1000)
			})
		}
	})
	



	
	const des = ref([
		'1.禁用时间段每天最多可用设置5个',
		"2.当设置好一天的禁用时间，第二天如果相同可以点击【引用前一天设置的内容】快速设置禁用时间",
		"管理优先级： 时间管理 > 应用管理",
		{
			text: '3.使用帮助',
			type: 'timeManagement'
		}
	]);
	
	const weeks = ref([
		{
			e: 'Mon',
			c: '周一'
		},
		{
			e: 'Tue',
			c: '周二'
		},
		{
			e: 'Web',
			c: '周三'
		},
		{
			e: 'Thur',
			c: '周四'
		},
		{
			e: 'Fri',
			c: '周五'
		},
		{
			e: 'Sat',
			c: '周六'
		},
		{
			e: 'Sun',
			c: '周日'
		},
	])
	
	const weekImg = [
		'/static/icon/icon_day_one.png',
		'/static/icon/icon_day_two.png',
		'/static/icon/icon_day_three.png',	
		'/static/icon/icon_day_four.png',
		'/static/icon/icon_day_five.png',
	]
	
	const time = ref({
			  currentActive: {
				  index: 0,// 当前点击在星期几
				  week: "Mon" // 星期几
			  },
			  Mon:[], // 星期一禁用时间
			  Tue:[], // 星期二禁用时间
			  Web:[], // 星期三禁用时间
			  Thur:[],// 星期四禁用时间
			  Fri:[],// 星期五禁用时间
			  Sat:[],// 星期六禁用时间
			  Sun:[]// 星期日禁用时间
		});
	const currentWeek = computed(() => {
		return time.value[time.value.currentActive.week]
	})
	// 查询某一天是否有设置禁用时间
	const queryLen = (w) => {
		return time.value[w.e].length > 0
	}
	// 前一段时间的结束时间
	const preEndTime = () => {
		const week = time.value[time.value.currentActive.week]
		console.log('week', week)
		const len = week.length;
		if(len === 0 || len === 1){
			return "00:00"
		} else {
			return week[len - 2]["endTime"]
		}
	}
	const clickWeek = (index: number, week) => {
		time.value.currentActive = {
			index,
			week
		}
		showTime.value = false;
		setTimeout(() => {
			showTime.value = true;
		})
	}
	//  如果最后一段区间的时间的结束时间为23:59那么不能再继续添加时间段了
	const stopAddTime = () => {
		const w = time.value.currentActive.week;
		const len = time.value[w].length;
		const ENDTME = 'endTime'
		const STOPTIME = '23:59'
		return time.value[w][len - 1][ENDTME] === STOPTIME
	}
	
	// 当再次添加时间段的时候，设置开始时间为上一个时间段的结束时间，结束时间为23:59
	const setAddNewTime = () => {
		const w = time.value.currentActive.week;
		const len = time.value[w].length;
		const ENDTME = 'endTime'
		return{
			startTime: time.value[w][len - 1][ENDTME],
			endTime:'23:59'
		}
	}
	// 当前这个星期是空，一条数据都没有的情况
	const curWeekIsEmpt = () => {
		const w = time.value.currentActive.week;
		const len = time.value[w].length;
		const defaultTime = {startTime: '00:00', endTime:'23:59'};
		const isEmpt = len === 0;
		if(isEmpt){
			time.value[w].push(defaultTime)
		}
		return isEmpt;
	}
	
	

	// 取消新添加时间
	const onCancelNewAddTime = () => {
		newAddTimePopup.value = false
		newAddTimeRef.value.close()
	}
	// 添加新时间具体的操作
	const onAddNewTime = () => {
		if(disabledAddTime.value){
			return;
		}
		disabledAddTime.value = true
		console.log("时间", addStartTime.value, addEndTime.value)
		const w = time.value.currentActive.week;
		// const len = time.value[w].length === 0 ? 0 : time.value[w].length
		const newTimeItem = {
			startTime: addStartTime.value,
			endTime: addEndTime.value
		}
		time.value[w].push(newTimeItem)
		showTime.value = false;
		
		const callback = (resBool: boolean) => {
			if(resBool){ 
				patternParentsQuery();
			}
			showTime.value = true
			newAddTimePopup.value = false
			newAddTimeRef.value.close()
			setTimeout(() => {
				disabledAddTime.value = false
			}, 3000)
		}
		patternParentsSetting({cb: callback});	
		
		
		
		// const w = time.value.currentActive.week;
		// if(curWeekIsEmpt()){
		// 	patternParentsSetting();
		// 	newAddTimePopup.value = false
		// 	return
		// }
		// if(stopAddTime()){
		// 	uni.showToast({
		// 		title:"无法再次添加，最终时间为23:59",
		// 		icon:"none"
		// 	})
		// 	return;
		// }
		// if(time.value[w]?.length < 5){			
		// 	time.value[w].push(setAddNewTime());
		// 	patternParentsSetting();
		// 	newAddTimePopup.value = false
		// } else {
		// 	uni.showToast({
		// 		title:"一天最多只能添加5个时间段",
		// 		icon:"none"
		// 	})
		// }
	}
	// 添加时间段
	const addDisableTime = () => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		const w = time.value.currentActive.week;
		const len = time.value[w].length;
		if(len === 0){
			newAddTimePopup.value = true
			newAddTimeRef.value.open()
			return
		}
		if(stopAddTime()){
			uni.showToast({
				title:"无法再次添加，最终时间为23:59",
				icon:"none"
			})
			return;
		}
		if(time.value[w]?.length >= 5){
			uni.showToast({
				title:"一天最多只能添加5个时间段",
				icon:"none"
			})
			return
		} else {
			const { startTime }= setAddNewTime()
			addStartTime.value = startTime // todo 数据过来了，页面没更新过来
			addEndTime.value ="23:59"
		}
		newAddTimePopup.value = true
	    newAddTimeRef.value.open()
	}
	const showTime = ref(true)
	const removeTime = (i: number) => {
		if(!mock.isLogged()){
			tipBoundStudent();
			return
		}
		const w = time.value.currentActive.week;
		time.value[w].splice(i,1);
		showTime.value = false;
		setTimeout(() => {
			showTime.value = true;
			patternParentsSetting({type: 'remove'});
		})		
	}
	// 设置禁用时间段
	interface patternParentsSettingProps{
		type?: 'remove'
		cb?: (res: boolean) => void
	}
	const  patternParentsSetting = async ({ type, cb }: patternParentsSettingProps = {}) => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log('没有学生id')
			return;
		}
		try{
			const filterData = (arr: Array<{startTime: string, endTime: string}>, startTime ='startTime', endTime ='endTime') => {
				const colon = ":";
				return arr.filter(t => t[startTime].includes(colon) && t[endTime].includes(colon));
			}
			const params = {
					patternParentSlots: [
						{
							dayTheWeek: 1,
							patternTimeScopes: filterData(time.value['Mon'])
						},
						{
							dayTheWeek: 2,
							patternTimeScopes: filterData(time.value['Tue'])
						},
						{
							dayTheWeek: 3,
							patternTimeScopes: filterData(time.value['Web'])
						},
						{
							dayTheWeek: 4,
							patternTimeScopes: filterData(time.value['Thur'])
						},
						{
							dayTheWeek: 5,
							patternTimeScopes: filterData(time.value['Fri'])
						},
						{
							dayTheWeek: 6,
							patternTimeScopes: filterData(time.value['Sat'])
						},
						{
							dayTheWeek: 7,
							patternTimeScopes: filterData(time.value['Sun'])
						}
					],
					studentId,
					type: 1
			}
			const { status ,data} = await homeServer.patternParentsSetting(params as any);
			if(status === '200'){
				const title = type === "remove" ? '删除成功': '设置成功'
				uni.showToast({
					title,
					icon:"success"
				})
				cb?.(true)
			}
			cb?.(false)
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	const validateTime = (s, e) => {
		const [s_s, s_e] = s.split(":").map(t => Number(t));
		const [e_s, e_e] = e.split(":").map(t => Number(t));
		return e_s > s_s || (e_s === s_s && e_e > s_e);
	}
	
	const onSelectStartTimeCB = (start_time: string, i: number) => {
		const w = time.value.currentActive.week;
		time.value[w][i]['startTime'] = start_time
		patternParentsSetting();
	}
	
	const onSelectEndTimeCB = (end_time: string, i:number, cb: Function) => {
		const w = time.value.currentActive.week;
		const currentLen = time.value[w].length;
		if(currentLen - 1 > i){ // 当前点击的结束时间，下面还有一个时间段，因此，这个结束时间不能超过下个时间段的开始时间
			const nextStart = time.value[w][i+1]["startTime"];
			if(!validateTime(end_time, nextStart) ){
				uni.showToast({
					title:"不能大于下一个时间段的开始时间",
					icon:"none",
					duration:3000
				})
				return;
			}
		} 
		time.value[w][i]['endTime'] = end_time;
		patternParentsSetting();
		cb?.()
	}
	
	
	onUnload(() => {
		console.log("页面销毁了 ONuNLAOD")
		if(timeTotal.value === defaultTimeTips && checked.value ) {
			console.log("页面销毁了 需要重置时间开关")
			notShowMsg.value = true
			onChangeSwitch({detail: false})
		}
	})
	

</script>

<style lang="scss">
	page {
		background-color: #f5f9fa;
	}
</style>

<style lang="scss" scoped>
	.time-manage-page{
		.mange-time-slot{
			margin-top: 40upx;
			padding: 40upx;
			border-top-left-radius: 16upx;
			border-top-right-radius: 16upx;
			background-color: #fff;
			.available-use-time{
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1upx solid #f3f3f3; 
				line-height: 80upx;
				height: 80upx;
				margin-bottom: 20upx;
				.left-txt{
					font-size: 30upx;
					color: #000;
				}
				.time{
					display: flex;
					justify-content: flex-end;
					align-items: center;
					font-size: 30upx;
					color: #777;
				}
			}
			.title{
				font-size: 30upx;
				font-weight: bold;
				color: #000;
			}
			.des{
				margin: 20upx 0 40upx 0;
				font-size: 25upx;
				font-weight: 400;
				color: #081A2A;
					background-color: #fff;
			}
			.week{
				display: flex;
				justify-content: space-between;
				align-items: center;
				background-color: #fff;
				.week-day{
					background: #F7FBFE;
					border-radius: 16upx;
					display: flex;
					flex-direction: column;
					padding: 5upx 18upx;
					text-align: center;
					.e{
						;
						font-weight: 400;
						font-size: 24upx;
						color: #999999;
						text-align: center;
					}
					.c{
						font-weight: 400;
						font-size: 28upx;
						color: #081A2A;
						text-align: center;
					}
				}
				
				.haveData{
					// background-color: #eafaf4;
					background-color: #b5f7de;
					.e{
						color: #a0a0a0;
					}
					.c{
						color: #636363;
					}
				}
				.activeWeekDay{
					background-color: #2BC888;
					.e{
						color: #cbe6db;
					}
					.c{
						color: #e6f6ef;
					}
				}
				
				
			}
			
			
			
			.time-manage{
				margin-top: 40upx;
				padding-bottom: 100upx;
				background-color: #fff;
				
				.bg{
					width: 100%;
					height: 40upx;
					background-color: #f5f9fa;
				}
				.header{
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 40upx;
					padding-top: 40upx;
					.title{
						font-family: PingFang SC, PingFang SC;
						font-weight: 800;
						font-size: 32upx;
						color: #081A2A;
						text-align: left;
						font-style: normal;
					}
					.btn{
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 28upx;
						color: #2bc888;
						text-align: right;
						font-style: normal;
						text-transform: none;
						background-color: #eafaf4;
						padding:10upx 20upx;
						border-radius: 25upx;
					}
				}
				.control-time-list-item{
					display: flex;
					justify-content: space-between;
					align-items: center;
					border-bottom: 1upx solid #F7FBFE;
					padding-bottom: 10upx;
					padding-top: 10upx;
					.control-time{
						display: flex;
						align-items: center;
						justify-content:center;
						.serial{
							
						}							
					}
					.time-input{}
					.action-btn{
						display: flex;
						justify-content: space-between;
						align-items: center;
						.setting{
							background-color: #eafaf4;
							color:#2bc888;
							font-weight: 800;
							width: 100upx;
							height: 50upx;
							font-size: 24upx;
							border-radius: 25upx;
							line-height: 50upx;
							text-align: center;
							margin-right:10upx;
						}
						.dele{
							width: 50upx;
							height: 50upx;
							// background-color: #fff0f0;
							text-align: center;
							border-radius: 50%;
						}
					}
				}
				.empt{
					// padding-bottom: 100upx;
					font-size: 32upx;
					color:#cacaca;
					width: 100%;
					padding: 100upx 0;
					text-align: center;
				}
			}
		}
	}
	
	
	
	
	.add-white-app-post-bottom{
		position: fixed;
		left: 0;
		right: 0;
		bottom: 20upx;
		
		margin: 0 auto;
		display: flex;
		justify-content: center;
		align-items: center;
		// background-color: #eff6fb;
		background-color: #2BC888;
		width: 40%;
		border-radius: 40upx;
		padding: 20upx;
		font-size: 30upx;
		// color: #2BC888;
		color: #fff;
		.txt{
			margin-left: 20upx;
		}
	}
	
	
	.top-switch{
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		padding: 20upx 40upx;
		border-bottom:1upx solid #f1f1f1;
		.title{
			font-size: 30upx;
			text-align: center;
			color: #0c0c0c;
			margin-bottom: 20upx;
		}
		.txt-switch{
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			.left-txt{
					font-size: 26upx;
			}
		}
	}
	

	
</style>

// <style lang="scss">
// 	.time-manage-page{
// 		.custom-flotter{
// 			.van-picker{
// 				.van-picker__toolbar {
// 					display: flex;
// 					justify-content: center;
// 					align-items: center;
// 					.van-picker__cancel{
// 						color: #090;
// 						font-weight: 800;
// 						font-size: 30upx;
// 						text-align: center;
// 						background-color: #ccc;
// 						border-radius: 5upx;
// 					}
// 					.van-picker__confirm{
// 						color: #fff;
// 						font-weight: 800;
// 						font-size: 30upx;
// 						text-align: center;
// 						background-color: #090;
// 						border-radius: 5upx;
// 					}
// 				}
// 			}
// 		}
// 	}

// </style>
<style>
	.time-manage-page .van-picker__toolbar {
		display: flex;
		justify-content: center;
		align-items: center;
		line-height: 1;
		height:auto;
	}
	.time-manage-page .van-picker__cancel{
		color: #4bb15d;
		font-weight: 800;
		font-size: 30upx;
		text-align: center;
		background-color: #f2f2f2;
		border-radius: 10upx;
		padding: 20upx 80upx;
		margin-right: 20upx;
	}
	
	.time-manage-page .van-picker__confirm{
		color: #feffff;
		font-weight: 800;
		font-size: 30upx;
		text-align: center;
		background-color: #57bf6a;
		border-radius: 10upx;
		padding: 20upx 80upx;
		margin-left: 20upx;
	}
	
	
.picker-view {
	width: 750upx;
	height: 600upx;
	margin-top: 20upx;
	
}

.picker-view .item {
	line-height: 100upx;
	text-align: center;
}
	
</style>

<style lang="scss">
	.hideHeightStyle{
		height:0;
		// .van-picker{
		// 	height: 0;
		// 	.van-picker__columns{
		// 		height: 0 !important;
		// 	}
		// }
	}
	
	.customSwitch{
		padding: 80upx 0;
	}
	
	.new-add-time-content{
		min-height: 300upx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.footer{
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		margin-bottom: 100upx;
		.basic-footer-new-time {
			width: 150upx;
			height: 80upx;
			border: none;
			color: #fff;
			font-size: 26upx;
			text-align: center;
			line-height: 80upx;
		}
		.cancel-new-time{
			background-color: #ccc;
		}
		.enter-new-time{
			background-color: #2BC888;
		}
	}
</style>


<style lang="scss">
.add-close{
	position: relative;
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	padding: 20upx 40upx;
	.title-position{
		position: absolute;
		left: 0;
		right: 0;
		margin: auto;
	}
}


.close-icon-postion{
	position: absolute;
	z-index: 10;
	right: 20upx;
	top:0;
}



.time-lang-control{
	display: flex;
	justify-content: space-evenly;
	width: 100%;
	height: 100upx;
	margin: 20upx 0;
	.base-time-lang {
		width: 180upx;
		height:90upx;
		line-height: 90upx;
		text-align: center;
		color: #fff;
		border-radius: 15upx;
		font-size: 32upx;
	}
	.oncancel-btn{
		background-color: #ececec;
		color: #2BC888;
	}
	.onSure-btn{
		background-color: #2BC888;
	}
}

.showPickerTimeModal{
	position: fixed;
	z-index: 9999;
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	display: flex;
	justify-content: center;
	align-items: center;
}
.ks-picker-view-column{
	.item{
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
</style>